from django.shortcuts import render
import json
import logging
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.db import connection
from django.utils import timezone
from .services import ChatbotService
from .models import ChatSession, ChatMessage

logger = logging.getLogger(__name__)

def chatbot_page(request):
    """聊天机器人页面"""
    # 尝试从URL参数中获取会话ID
    url_session_id = request.GET.get('session_id')
    
    # 从会话中获取保存的会话ID
    session_id = request.session.get('chatbot_session_id')
    
    # 如果URL中有会话ID，优先使用URL中的
    if url_session_id:
        session_id = url_session_id
    
    user_id = request.user.pk if request.user.is_authenticated else None
    
    # 初始化聊天机器人服务
    chatbot_service = ChatbotService()
    
    # 创建或获取会话
    session = chatbot_service.create_or_get_session(session_id, user_id)
    
    # 检查会话是否过期(超过24小时没有活动)
    if session.last_activity and (timezone.now() - session.last_activity).days >= 1:
        # 获取新的系统提示词(包含最新用户数据)
        system_prompt = chatbot_service.get_system_prompt(user_id)
        
        # 更新系统消息
        system_message = ChatMessage.objects.filter(
            session_id=session,
            role="system"
        ).first()
        
        if system_message:
            system_message.content = system_prompt
            system_message.timestamp = timezone.now()
            system_message.save()
    
    # 将会话ID保存到用户会话
    request.session['chatbot_session_id'] = session.session_id
    
    # 获取历史消息
    messages = chatbot_service.get_message_history(session)
    
    # 添加用户浏览行为记录
    if request.user.is_authenticated:
        with connection.cursor() as cursor:
            cursor.execute("""
                INSERT INTO tb_user_behavior 
                (user_id, session_id, action_type, object_type, object_id, url, query, user_agent, ip_address, create_time)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, NOW())
            """, [
                request.user.pk,
                request.session.session_key,
                'view',
                'chatbot', 
                0,
                request.path,
                '',
                request.META.get('HTTP_USER_AGENT', ''),
                request.META.get('REMOTE_ADDR', ''),
            ])
    
    context = {
        'session_id': session.session_id,
        'messages': messages,
    }
    
    return render(request, 'chatbot/chat.html', context)

@csrf_exempt
def chatbot_api(request):
    """聊天机器人API"""
    if request.method != 'POST':
        return JsonResponse({'error': '仅支持POST请求'}, status=405)
    
    try:
        data = json.loads(request.body)
        message = data.get('message')
        session_id = data.get('session_id')
        
        if not message or not session_id:
            return JsonResponse({'error': '缺少必要参数'}, status=400)
        
        user_id = request.user.pk if request.user.is_authenticated else None
        
        # 初始化聊天机器人服务
        chatbot_service = ChatbotService()
        
        # 获取会话
        session = chatbot_service.create_or_get_session(session_id, user_id)
        
        # 获取AI响应
        response = chatbot_service.get_response(session, message)
        
        # 添加用户聊天行为记录
        if request.user.is_authenticated:
            with connection.cursor() as cursor:
                cursor.execute("""
                    INSERT INTO tb_user_behavior 
                    (user_id, session_id, action_type, object_type, object_id, url, query, user_agent, ip_address, create_time)
                    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, NOW())
                """, [
                    request.user.pk,
                    request.session.session_key,
                    'chat',
                    'chatbot', 
                    0,
                    request.path,
                    message[:255] if message else '',  # 限制长度，避免数据库错误
                    request.META.get('HTTP_USER_AGENT', ''),
                    request.META.get('REMOTE_ADDR', ''),
                ])
        
        return JsonResponse({
            'response': response,
            'session_id': session.session_id
        })
        
    except Exception as e:
        logger.exception(f"聊天API处理错误: {str(e)}")
        return JsonResponse({'error': '服务器内部错误'}, status=500)

@login_required
def chat_history(request):
    """用户聊天历史"""
    user_id = request.user.pk
    
    # 获取该用户的所有会话
    sessions = ChatSession.objects.filter(user_id=user_id).order_by('-last_activity')
    
    # 为每个会话获取最后一条消息
    for session in sessions:
        last_message = ChatMessage.objects.filter(
            session_id=session,
            role='assistant'
        ).order_by('-timestamp').first()
        
        session.last_message = last_message.content if last_message else '无消息'
    
    context = {
        'sessions': sessions
    }
    
    return render(request, 'chatbot/history.html', context)
